﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using G.Navigate;
using G.Net.Oauth;

namespace G.WeiBo
{
    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();
            var dictionaries = Resources.MergedDictionaries;

            dictionaries.Clear();

            dictionaries.Add(new ResourceDictionary { Source = new Uri(ThemeHelp.GetThemePath(ThemeHelp.GetThemeType()), UriKind.Relative) });

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                //Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disable user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
            Net.Oauth.Oauth2Config.Request_Authorize_Url = "https://api.weibo.com/oauth2/authorize";
            Net.Oauth.Oauth2Config.ClientID = "1029251523";
            Net.Oauth.Oauth2Config.ClientSecret = "5725cf318a29181031193bc168aa7c8e";
            Net.Oauth.Oauth2Config.RedirectUri = "http://www.baidu.com";
            Net.Oauth.Oauth2Config.Token_Authorize_Url = "https://api.weibo.com/oauth2/access_token";
            //OauthConfiger.AppKey = "1029251523";
            //OauthConfiger.AppSecret = "5725cf318a29181031193bc168aa7c8e";
            //OauthConfiger.AccessToken = OAuthAccessToken.Load(APPConfig.SaveTokenName);

        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            G.BI.BIConfig.APPKey = "ceeebc8f-6d82-4cf7-8c12-956080a798d8";
            G.BI.BIClient.SendEvent(new G.BI.AppStartEvent() { DeviceId = G.UserDeviceInfo.GetDeviceUniqueId(), StartTime = DateTime.Now }, (s) =>
            {
                var aa = s;
            });
            List<LogData> logs = LogData.ReadLogData();
            if (logs != null && logs.Count > 0)
            {
                if (MessageBox.Show("上次的退出非正常退出，是否报告异常信息？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    foreach (var item in logs)
                    {
                        Microsoft.Phone.Tasks.EmailComposeTask task = new Microsoft.Phone.Tasks.EmailComposeTask();
                        task.Body = item.Date.ToString() + "\r\n" + item.Message;
                        task.Subject = item.Title;
                        task.To = "dagehaoshuang@163.com";
                        task.Show();
                        break;
                    }
                    System.Threading.Thread.Sleep(1000);
                    LogData.Clear();
                }
            }
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {

        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject.Message == "0x8000ffff")//如果错误信息为0x8000ffff，那么是由于回退太快并且回退到首页，
            {
                e.Handled = true;
                return;
            }

            if (!(e.ExceptionObject is ExitExeption))
            {
                LogData logdata = new LogData(DateTime.Now, "微博客户端Bug报告", "页面：" + this.RootFrame.Content.GetType().Name + "\r\n" +
                            "正在处理的元素:" + System.Windows.Controls.Primitives.LayoutInformation.GetLayoutExceptionElement(this.RootFrame.Dispatcher) + "\r\n" +
                          "异常信息：" + e.ExceptionObject.Message + "\r\n" + "异常堆栈：" + e.ExceptionObject.StackTrace);
                LogData.Save(logdata);
            }
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;
            RootFrame.Navigating += RootFrame_Navigating;
            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;
            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            RootFrame.Navigating -= RootFrame_Navigating;
            if (Oauth2Valid.IsLogin(WebAPI.APIConfig.AppName))
            {
                e.Cancel = true;
                this.RootFrame.Dispatcher.BeginInvoke(() =>
                {
                    RootFrame.Navigate(new Uri("/View/Index.xaml", UriKind.Relative));
                });
            }
       
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;
            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}